package com.firemoss.ui.blanket
{
	import flash.display.DisplayObjectContainer;
	import flash.utils.Dictionary;
	
	import mx.core.UIComponent;
	import mx.managers.ISystemManager;

	/**
	 * Default implementation of IBlanketDisplayObjectContainerLocator used within
	 * Blanket.  (Ab)uses the SystemManager of a given component to shove
	 * a Blanket-specific UIComponent subclass into the first position in its 
	 * assigned rendering "layer" if it doesn't exist.  Once it exists,
	 * we return it as the DisplayObjectContainer to use.
	 */
	public class SystemManagerLayerBlanketDisplayObjectContainerLocator implements IBlanketDisplayObjectContainerLocator
	{
		
		/**
		 * Name of the pseudo-childlist in the system manager to use.  Subclasses must assign in their constructor!
		 */
		public var systemManagerChildListName : String
		
		/**
		 * Lookup of blanket containers by system manager.  Strong keys:  this is the only ref to
		 * them unless they have children!
		 */
		private var blanketContainers : Dictionary = new Dictionary()
		
		/**
		 * args.target == the UIComponent that's the target of the overlay
		 */
		public function findDisplayObjectContainer(args:Object=null):DisplayObjectContainer
		{
			if ( !args.hasOwnProperty( "target" ) || !( args.target is UIComponent ) )
			{
				throw new Error("For DefaultBlanketDisplayObjectContainerLocator's findDisplayObjectContainer(), pass \"target\" as a member of the args structure, and make sure it's non-null and a UIComponent.")
			}
			
			if ( !systemManagerChildListName )
			{
				throw new Error("Please assign 'systemManagerChildListName' a value for your implementation.")
			}
			
			var target : UIComponent = args.target as UIComponent
			
			// Get its system manager and make sure its first "tooltip" child is really our shoved-in container
			var sysManager : ISystemManager = target.systemManager
			var container : OverlayUIComponent
			
			if ( !sysManager )
			{
				throw new Error("Target had no system manager:  not ready for an overlay!")
			}
			
			// If no container for this system manager, add one.
			if ( !blanketContainers[ sysManager ] )
			{
				container = new OverlayUIComponent()
				sysManager[systemManagerChildListName].addChildAt( container, 0 )
				blanketContainers[ sysManager ] = new Dictionary()
				blanketContainers[ sysManager ][ systemManagerChildListName ] = new Dictionary()
			}
			else
			{
				container = blanketContainers[ sysManager ][ systemManagerChildListName ]
			}
			
			return container
		}
		
	}
}